import SwiftUI
import KSPlayer
import Combine

// DetailView 专用的视频播放器 - 只播放第一个片段
struct DetailVideoPlayer: View {
    let videoURL: String
    let videoId: String
    let isMuted: Bool
    let shouldFillScreen: Bool  // 是否铺满屏幕
    let videoType: Int  // 视频类型
    
    @StateObject private var detailPlaybackManager = DetailPlaybackManager.shared
    @State private var playerCoordinator = KSVideoPlayer.Coordinator()
    @State private var options = KSOptions()
    @State private var isPlayerReady = false
    @State private var errorMessage: String?
    @State private var cancellables = Set<AnyCancellable>()
    
    init(videoURL: String, videoId: String, isMuted: Bool = true, shouldFillScreen: Bool = true, videoType: Int = 1) {
        self.videoURL = videoURL
        self.videoId = videoId
        self.isMuted = isMuted
        self.shouldFillScreen = shouldFillScreen
        self.videoType = videoType
        
        print("🎬 DetailVideoPlayer 初始化:")
        print("   - videoId: \(videoId)")
        print("   - shouldFillScreen: \(shouldFillScreen)")
        print("   - videoType: \(videoType)")
        print("   - isScaleAspectFill: \(videoType == 1)")
        print("   - isMuted: \(isMuted)")
    }
    
    var body: some View {
        // DetailView 不使用缓存，直接使用原始URL
        let actualVideoURL = videoURL
        
        let _ = {
            print("🎬 DetailVideoPlayer 视频源:")
            print("   - 原始URL: \(videoURL)")
            print("   - 实际URL: \(actualVideoURL)")
            print("   - 使用缓存: 否 (DetailView禁用缓存)")
        }()
        
        if let url = URL(string: actualVideoURL) {
            ZStack {
                KSVideoPlayer(
                    coordinator: playerCoordinator,
                    url: url,
                    options: options
                )
                .onStateChanged { layer, state in
                    handleStateChange(layer: layer, state: state)
                }
                .aspectRatio(contentMode: .fit)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                
                .onAppear {
                    setupPlayer()
                    // DetailView 不进行缓存
                    
                    // 立即开始播放
                    detailPlaybackManager.startPlaying(videoId: videoId)
                    
                    // 监听 DetailView 播放管理器状态变化
                    detailPlaybackManager.$currentPlayingVideoId
                        .sink { currentVideoId in
                            handlePlaybackManagerStateChange(currentVideoId: currentVideoId)
                        }
                        .store(in: &cancellables)
                    
                    detailPlaybackManager.$isPlaying
                        .sink { isPlaying in
                            handlePlayingStateChange(isPlaying: isPlaying)
                        }
                        .store(in: &cancellables)
                }
                .onDisappear {
                    // 停止播放并释放资源
                    playerCoordinator.playerLayer?.pause()
                    playerCoordinator.playerLayer?.stop()
                    cancellables.removeAll()
                }
                
                // 加载指示器
                if !isPlayerReady {
                    VStack(spacing: 12) {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            .scaleEffect(1.2)
                        
                        
//                        if let errorMessage = errorMessage {
//                            Text("播放失败: \(errorMessage)")
//                                .foregroundColor(.red)
//                                .font(.caption)
//                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.black.opacity(0.3))
                }
            }
        } else {
            Text("无效的视频URL")
                .foregroundColor(.red)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.black)
        }
    }
    
    // MARK: - 私有方法
    
    private func setupPlayer() {
        // DetailView 专用配置 - 只播放第一个片段
        options.isSecondOpen = true
        options.isAccurateSeek = true
        options.isLoopPlay = true  // DetailView 循环播放
        options.isSeekedAutoPlay = true
        
        // 设置使用 MEPlayer
        KSOptions.secondPlayerType = KSMEPlayer.self
        
         // 设置视频内容模式
        playerCoordinator.isScaleAspectFill = videoType == 1
        
        // 设置音量和静音状态
        playerCoordinator.playbackVolume = 1.0
        playerCoordinator.isMuted = isMuted
        
 
        
        // m3u8 专用优化配置
        if videoURL.hasSuffix(".m3u8") {
            
            // 秒开配置
            options.isSecondOpen = true
            options.codecLowDelay = true
            
            // HLS 专用优化配置
            options.formatContextOptions["reconnect"] = 1
            options.formatContextOptions["reconnect_streamed"] = 1
            options.formatContextOptions["scan_all_pmts"] = 1
            options.formatContextOptions["fflags"] = "fastseek"
            options.formatContextOptions["flags"] = "low_delay"
            
            // 网络优化
            options.formatContextOptions["timeout"] = 5000000
            options.formatContextOptions["rw_timeout"] = 5000000
            options.formatContextOptions["analyzeduration"] = 2000000
            options.formatContextOptions["probesize"] = 2000000
            
            // 设置 User-Agent
            options.userAgent = "KSPlayer/1.0 (iOS; HLS; DetailView)"
            
            // 启用硬件解码
            options.hardwareDecode = true
            options.asynchronousDecompression = true
            
            // 减少重试次数
            options.formatContextOptions["max_retry_count"] = 1
            options.formatContextOptions["retry_interval"] = 500000
            
            // 允许 HTTP/HTTPS 协议访问
            options.formatContextOptions["protocol_whitelist"] = "file,http,https,crypto,data"
            
            
            // 禁用自动选择内嵌字幕
            options.autoSelectEmbedSubtitle = false
        }
        
        print("🔧 DetailView 专用播放器配置完成")
        print("⚡ 秒开: \(options.isSecondOpen)")
        print("🔄 循环播放: \(options.isLoopPlay)")
        print("🔇 静音状态: \(isMuted)")
    }
    
    
    private func handleStateChange(layer: KSPlayerLayer, state: KSPlayerState) {
        DispatchQueue.main.async {
            print("🎬 DetailView 播放状态变化: \(state)")
            
            switch state {
            case .readyToPlay:
                self.isPlayerReady = true
                self.errorMessage = nil
                self.detailPlaybackManager.setVideoReady(true)
                print("✅ DetailView 播放器准备就绪")
                
                // 立即开始播放，不等待其他条件
                print("▶️ DetailView 开始自动播放")
                layer.play()
                
            case .preparing:
                self.isPlayerReady = false
                self.errorMessage = nil
                print("🔄 DetailView 播放器准备中...")
                
            case .bufferFinished:
                self.isPlayerReady = true
                print("✅ DetailView 缓冲完成")
                
                // 缓冲完成后立即播放
                print("▶️ DetailView 缓冲完成后开始播放")
                layer.play()
                
            case .buffering:
                self.isPlayerReady = false
                print("⏳ DetailView 正在缓冲...")
                
            case .playedToTheEnd:
                print("🏁 DetailView 播放完成")
                // DetailView 循环播放，自动重新开始
                if self.detailPlaybackManager.shouldPlay(videoId: self.videoId) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        layer.play()
                    }
                }
                
            case .error:
                self.errorMessage = "播放失败"
                self.isPlayerReady = false
                print("❌ DetailView 播放出错")
                
            case .paused:
                print("⏸️ DetailView 播放暂停")
                
            case .initialized:
                print("🚀 DetailView 播放器初始化完成")
                
            @unknown default:
                print("❓ DetailView 未知播放状态: \(state)")
            }
        }
    }
    
    private func handlePlaybackManagerStateChange(currentVideoId: String?) {
        guard let playerLayer = playerCoordinator.playerLayer else { return }
        
        if currentVideoId == videoId {
            print("▶️ DetailView 应该播放: \(videoId)")
            if isPlayerReady && detailPlaybackManager.isPlaying {
                DispatchQueue.main.async {
                    playerLayer.play()
                }
            }
        } else {
            print("⏸️ DetailView 应该暂停: \(videoId)")
            DispatchQueue.main.async {
                playerLayer.pause()
            }
        }
    }
    
    private func handlePlayingStateChange(isPlaying: Bool) {
        guard let playerLayer = playerCoordinator.playerLayer else { return }
        
        if detailPlaybackManager.currentPlayingVideoId == videoId {
            if isPlaying {
                print("▶️ DetailView 恢复播放")
                DispatchQueue.main.async {
                    playerLayer.play()
                }
            } else {
                print("⏸️ DetailView 暂停播放")
                DispatchQueue.main.async {
                    playerLayer.pause()
                }
            }
        }
    }
}
